package org.spruice;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * User: mrettig
 * Date: Feb 7, 2009
 * Time: 8:25:21 PM
 */
public class FactoryConfig<T, R> {
    private BeanConfig<T> factoryBean;
    private Binder b;
    private Class<R> targetClzz;
    private String create;
    private Object[] createArgs;

    public FactoryConfig(BeanConfig<T> factoryBean, Binder b, Class<R> targetClzz) {
        this.factoryBean = factoryBean;
        this.b = b;
        this.targetClzz = targetClzz;
    }

    public T createWith() {
        MethodInterceptor method = new MethodInterceptor() {
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                create = method.getName();
                createArgs = args;
                return null;
            }
        };
        return factoryBean.createProxy(method);
    }

    public BeanConfig<R> createBean(String beanName) {
        return b.factory(beanName, factoryBean.getName(), create, targetClzz, createArgs);
    }
}
